
package net.biaji.android.alephclient.account;

import net.biaji.alephclient.LibAgent;
import net.biaji.alephclient.NotLoginException;
import net.biaji.android.alephclient.AgentSingleton;
import net.biaji.android.alephclient.data.DataFusionManager;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.content.AbstractThreadedSyncAdapter;
import android.content.ContentProviderClient;
import android.content.Context;
import android.content.SyncResult;
import android.os.Bundle;
import android.util.Log;

/**
 * @author biAji<biaji@biaji.net>
 */
public class SyncAdapter extends AbstractThreadedSyncAdapter {
    private Context context;

    public SyncAdapter(Context context, boolean autoInitialize) {
        super(context, autoInitialize);
        this.context = context;
    }

    @Override
    public void onPerformSync(Account account, Bundle extras, String authority,
            ContentProviderClient provider, SyncResult syncResult) {
        String name = account.name;
        String password = AccountManager.get(context).getPassword(account);
        LibAgent agent = AgentSingleton.getInstance(name, password);
        if (agent == null) {
            syncResult.stats.numAuthExceptions++;
            return;
        }

        try {
            DataFusionManager.getInstance(this.context).updateBorrowInfo(agent.getBookInPocket());
        } catch (NotLoginException e) {
            Log.e("SyncAdapter", "Sync Error", e);
        }

    }
}
